import numpy as np
import pandas as pd
import random

dataSet =pd.read_csv('D:\python\shiyan\ionosphere.data',header=None)
dataSet.head()

def randSplit(dataSet, rate):
    l = list(dataSet.index) 
    random.shuffle(l) 
    dataSet.index = l 
    n = dataSet.shape[0] 
    m = int(n * rate) 
    train = dataSet.loc[range(m), :]
    test = dataSet.loc[range(m, n), :] 
    dataSet.index = range(dataSet.shape[0]) 
    test.index = range(test.shape[0]) 
    return train, test

def gnb_classify(train,test):
    labels = train.iloc[:,-1].value_counts().index 
    mean =[] 
    std =[] 
    result = [] 
    for i in labels:
        item = train.loc[train.iloc[:,-1]==i,:] 
        m = item.iloc[:,:-1].mean() 
        s = np.sum((item.iloc[:,:-1]-m)**2)/(item.shape[0]) 
        mean.append(m)
        std.append(s) 
    means = pd.DataFrame(mean,index=labels) 
    stds = pd.DataFrame(std,index=labels) 
    for j in range(test.shape[0]):
        iset = test.iloc[j,:-1].tolist()
        iprob = np.exp(-1*(iset-means)**2/(stds*2))/(np.sqrt(2*np.pi*stds)) 
        prob = 1
        for k in range(test.shape[1]-1): 
            prob *= iprob[k] 
            cla = prob.index[np.argmax(prob.values)] 
        result.append(cla)
    test['predict']=result
    acc = (test.iloc[:,-1]==test.iloc[:,-2]).mean() 
    print(f'模型预测准确率为{acc}')
    return test
for i in range(20):
    train,test = randSplit(dataSet,0.8)
    gnb_classify(train,test)
